package datastructures.stack;

/**
 * 数组实现栈
 *
 * @author hck
 */
public class ArrayStack {
    /**
     * 存数据
     */
    private int array[];
    /**
     * 记录当前数据指针
     */
    private int cursor = -1;

    public ArrayStack(int length) {
        array = new int[length];
    }

    /**
     * 入栈
     *
     * @param data
     */
    public void push(int data) {
        if (cursor == array.length - 1) {
            throw new RuntimeException("stack is full");
        }
        cursor++;
        array[cursor] = data;
    }

    /**
     * 出栈
     *
     * @return
     */
    public int pop() {
        if (cursor == -1) {
            throw new RuntimeException("stack is empty");
        }
        int data = array[cursor];
        cursor--;
        return data;
    }

    public void print() {
        if (cursor == -1) {
            System.out.println("[]");
        }
        System.out.print("[");
        for (int i = 0; i <= cursor; i++) {
            System.out.print(array[i]);
            if (i != cursor) {
                System.out.print(",");
            }
        }
        System.out.println("]");
    }
}
